#-*- coding: utf-8 -*-

import sqlite3

class Database():

	def __init__(self, filename):

		try:
			self.db = sqlite3.connect(filename)

		except Exception, e:
			print e

			self.db = sqlite3.connect(':memory:')
		
		#self.cursor = self.db.cursor()

	def execute(self, *args, **kwargs):
		result = self.cursor.execute(*args)
		return result

	def close(self):
		self.db.commit()
		self.cursor.close()

	def create(self):
		""" иницилизация """
		self.execute("CREATE TABLE IF NOT EXISTS settings(option, value)")
		self.execute("CREATE TABLE IF NOT EXISTS users(nick, jid, category, option, value)")

		self.db.commit()

	def table(self, tablename, tablecolumns):
		table = Table(self.db, tablename, tablecolumns)
		return table

	def __del__(self):
		#self.cursor.close()
		self.db.commit()
		self.db.close()


class Table():

	def __init__(self, db, name, content):
		self.db = db
		self.name = name
		self.content = content

		expression = 'create table %s(%s)' % (name, ', '.join(content))


		print expression
		self.cursor = self.db.cursor()
		self.cursor.execute(expression)
		#self.db.commit()

	def set(self, data):
		expression = 'insert into %s values(%s)' % (self.name, ', '.join(['?' for s in data]), )
		

		print expression
	
		self.cursor.execute(expression, data)

	def get(self):
		return self.cursor.execute('select * from %s' % self.name).fetchall()


if __name__ == "__main__":
	i = Database('*.db')



	t = i.table('settings', ('context', 'option', 'value'))
	t.set(('admin', 'name', 'fooo'))
	print t.get()

	#print i.execute("SELECT * FROM SQLITE_MASTER").fetchall()
	
	#print sqlite3.version
